package com.mzwise.tunnel.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.mzwise.tunnel.utils.EncryptUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult;
import me.chanjar.weixin.mp.bean.membercard.WxMpMemberCardActivatedMessage;

import java.io.File;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 卡卷相关工具
 */
public class TunnelMpCard {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * 小程序卡券扩展字段及签名生成算法
     * @param wxService
     * @return
     * @throws WxErrorException
     */
    public static Map<String, String> getSignature(String cardId, WxMpService wxService) throws Exception {
        String apiTicket = getCardApiTicket(wxService);
        Map<String, String> data = new HashMap<String, String>();
        data.put("api_ticket", apiTicket);
        long timestamp = System.currentTimeMillis() / 1000;
        data.put("timestamp", String.valueOf(timestamp));
        data.put("card_id", cardId);
        data.put("nonce_str", generateNonceStr());
        String s = generateSignature(data);
        data.put("signature", s);
        return data;
    }

    /**
     * 卡券 api_ticket
     * @return
     * @throws WxErrorException
     */
    private static String getCardApiTicket(WxMpService wxService) throws WxErrorException {
        return wxService.getCardService().getCardApiTicket();
    }

    /**
     * 卡券sha1签名生成算法。
     * @param data 待签名数据
     * @return 签名
     */
    private static String generateSignature(final Map<String, String> data) throws Exception {
        String[] str = {data.get("api_ticket"),data.get("timestamp"),data.get("card_id"),data.get("nonce_str")};
        Arrays.sort(str);
        String string = new String();
        for(int i=0; i<4; i++){
            string += str[i];
        }
        String signature = null;    //加密结果
        signature = EncryptUtils.getSha1(string);  //Sha1加密
        return signature;
    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }




    /**
     * 解密会员卡code
     * @param encryptCode
     * @return
     * @throws WxErrorException
     */
    public static String decryptCardCode(String encryptCode, WxMpService wxService) throws Exception {
        //获取微信请求token
//        wxMpconfig(WxmpService.findByMchId(mchId));
//        wxService.setWxMpConfigStorage(config);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("encrypt_code",encryptCode);
        String re= wxService.post("https://api.weixin.qq.com/card/code/decrypt", String.valueOf(jsonObject));
        //解析出返回的json串
        JSONObject object = new JSONObject(re);
        String errmsg=object.getStr("errmsg");
        String code=object.getStr("code");
        System.out.println(object);
        if ("ok".equals(errmsg)){
            System.out.println(object);
            return code;
        }else{
            throw new Exception("解密会员卡失败！");
        }

    }

    /**
     * 设置会员卡激活字段
     * @param card_id
     * @return
     * @throws WxErrorException
     */
    public static void activateUserForm(String card_id, WxMpService wxService) throws Exception {
        String params = "{\n" +
                "    \"card_id\": \""+card_id+"\",\n" +
                "    \"required_form\": {\n" +
                "        \"common_field_id_list\": [\"USER_FORM_INFO_FLAG_NAME\", \"USER_FORM_INFO_FLAG_MOBILE\"]\n" +
                "    }\n" +
                "}";
        String re= wxService.post("https://api.weixin.qq.com/card/membercard/activateuserform/set", params);
        //解析出返回的json串
        JSONObject object = new JSONObject(re);
        System.out.println(object);
        String errmsg=object.getStr("errmsg");
        if ("ok".equals(errmsg)){

        }else{
            throw new Exception("解密会员卡失败！");
        }
    }

    /**
     * 获取激活信息
     * @param activateTicket
     * @return
     * @throws WxErrorException
     */
    public static Map<String, String> activateTempInfo(String activateTicket, WxMpService wxService) throws Exception {
        String params = "{\n" +
                "    \"activate_ticket\" : \""+activateTicket+"\"\n" +
                "}";
        String re= wxService.post("https://api.weixin.qq.com/card/membercard/activatetempinfo/get", params);
        try {
            //解析出返回的json串
            JSONObject object = new JSONObject(re);
            System.out.println(object);
            String errmsg=object.getStr("errmsg");
            if (!"ok".equals(errmsg)) {
                throw new Exception("获取用户激活信息失败");
            }
            JSONArray fields = object.getJSONObject("info").getJSONArray("common_field_list");
            Map<String, String> map = new HashMap<String, String>();
            JSONObject row = null;
            for(int i=0; i<fields.size(); i++){
                row = fields.getJSONObject(i);
                if ("USER_FORM_INFO_FLAG_MOBILE".equals(row.getStr("name"))) {
                    map.put("phone", row.getStr("value"));
                } else if ("USER_FORM_INFO_FLAG_NAME".equals(row.getStr("name"))) {
                    map.put("username", row.getStr("value"));
                }
            }
            return map;
        } catch (Exception e) {
            throw new Exception("获取用户激活信息失败！");
        }
    }

    /**
     * 会员卡激活
     * @return
     */
    public static void cardActivated(String cardCode, String cardId, WxMpService wxService) throws Exception{
        WxMpMemberCardActivatedMessage wxMpMemberCardActivatedMessage=new WxMpMemberCardActivatedMessage();
        wxMpMemberCardActivatedMessage.setCardId(cardId);
        wxMpMemberCardActivatedMessage.setMembershipNumber(cardCode);
        wxMpMemberCardActivatedMessage.setCode(cardCode);
        //Todo 以下选填参数需要时打开
        String activateMemberCard= wxService.getMemberCardService().activateMemberCard(wxMpMemberCardActivatedMessage);
        //解析出返回的json串
        JSONObject object = new JSONObject(activateMemberCard);
        String errmsg=object.getStr("errmsg");
        System.out.println(object);
        if ("ok".equals(errmsg)){
            System.out.println(activateMemberCard);
        }else{
            throw new Exception("激活会员卡是失败！");
        }
    }

    /**
     * 根据消费金额计算积分
     * @param costMoney
     * @param costMoneyUnit
     * @param increaseBonus
     * @param maxIncreaseBonus
     */
    public static int moneyToBonus(BigDecimal costMoney, BigDecimal costMoneyUnit, int increaseBonus, int maxIncreaseBonus) {
        if (costMoney.compareTo(costMoneyUnit) == -1) {
            return 0;
        }
        int times = costMoney.divide(costMoneyUnit, 0, BigDecimal.ROUND_DOWN).intValue();
        int i = increaseBonus * times;
        if (i > maxIncreaseBonus) {
            return maxIncreaseBonus;
        }
        return i;
    }

    /**
     * 增加或修改积分接口
     */
    public static Boolean addBonus(String cardCode, String cardId, Integer bonus, WxMpService wxService) {
        if (bonus == null || bonus == 0) {
            return false;
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code", cardCode);
        jsonObject.put("card_id", cardId);
        //jsonObject.put("record_bonus","消费30元，获得3积分");//后期需要打开
        jsonObject.put("add_bonus", bonus);
        String post= null;
        try {
            post = wxService.post("https://api.weixin.qq.com/card/membercard/updateuser", String.valueOf(jsonObject));
            System.out.println("修改会员卡积分返回" + post);
        } catch (WxErrorException e) {
            e.printStackTrace();
            System.out.println("修改会员卡积分失败！");
            return false;
        }
        //解析出返回的json串
        JSONObject object = new JSONObject(post);
        String errmsg=object.getStr("errmsg");
        System.out.println(object);
        if ("ok".equals(errmsg)){
            return true;
        }else{
            System.out.println("修改会员卡积分失败！");
            return false;
        }
    }

}
